package com.lindenvalley.ch.network;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.HashMap;
import java.util.Map;

import android.content.Context;
import android.widget.Toast;

import com.lindenvalley.ch.R;
import com.lindenvalley.ch.content.Task;

public class OfflineTaskFactory implements TaskInterface {
	
	private static final String FILE_NAME = "tasks.ser";
	private File fileDataDir;
	private Map<Integer, Task> offLineTasks= new HashMap<Integer,Task>();
	private File outFile;

	public OfflineTaskFactory() {
		super();
		outFile = new File(fileDataDir, FILE_NAME);
	}

	@Override
	public void saveTask(Context mContext, Task task) {
		// TODO Auto-generated method stub
		offLineTasks = readTaks(mContext);
		offLineTasks.put(task.getTaskId(),task);
		fileDataDir = mContext.getFilesDir();
		try {
			
			if (outFile != null && outFile.exists()){
				outFile.createNewFile();
			}
			FileOutputStream outputStream = new FileOutputStream(outFile);
			ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
			objectOutputStream.writeObject(offLineTasks);
			objectOutputStream.flush();
			objectOutputStream.close();
			outputStream.close();
			Toast.makeText(mContext, R.string.updateSuccess, Toast.LENGTH_SHORT).show();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			task.settaskID(0);
			Toast.makeText(mContext, R.string.updateFail, Toast.LENGTH_SHORT).show();
		} catch (IOException e) {
			e.printStackTrace();
			task.settaskID(0);
			Toast.makeText(mContext, R.string.updateFail, Toast.LENGTH_SHORT).show();
		}

	}
	
	@SuppressWarnings("unchecked")
	public Map<Integer, Task> readTaks(Context mContext){
		Map<Integer, Task> tasks = null;
		File inTasks = new File(mContext.getFilesDir(), FILE_NAME);
		if (inTasks != null && inTasks.exists()){
			FileInputStream fileInputStream;
			try {
				fileInputStream = new FileInputStream(inTasks);
				ObjectInputStream inputStream = new ObjectInputStream(fileInputStream);
				tasks = (Map<Integer, Task>) inputStream.readObject();
				inputStream.close();
				fileInputStream.close();
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			} catch (StreamCorruptedException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			} catch (ClassNotFoundException e) {
				e.printStackTrace();
			}
			
		}
		return tasks;
	}
	
	public void deleteSerialyzedTask(Context mContext){
		File inTasks = new File(mContext.getFilesDir(), FILE_NAME);
		if (inTasks != null && inTasks.exists()){
			inTasks.delete();
		}
	}
}
